package org.andlisp.android;

import android.app.*;
import android.content.*;
import android.content.res.*;
import android.preference.*;
import android.util.*;
import android.widget.*;
import android.view.*;

public class SeekBarPreference extends DialogPreference implements SeekBar.OnSeekBarChangeListener
{
  final static String ATTR_NS_SEEKBAR = null;
  final static String ATTR_MIN = "seekbarpref_min";
  final static String ATTR_MAX = "seekbarpref_max";
  final static int DEFAULT_MIN = 0;
  final static int DEFAULT_MAX = 100;

  private TextView mText;
  private SeekBar mBar;
  private Context mCtx;
  private int mMax = DEFAULT_MAX;
  private int mMin = DEFAULT_MIN;

  public SeekBarPreference(Context context) {
    this(context, null);
  }

  public SeekBarPreference(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) {
    //super(context, attrs, defStyle);
    super(context, attrs);
    mCtx = context;

    String val;
    val = attrs.getAttributeValue(ATTR_NS_SEEKBAR, ATTR_MIN);
    mMin = val != null ? Integer.parseInt(val): DEFAULT_MIN;
    val = attrs.getAttributeValue(ATTR_NS_SEEKBAR, ATTR_MAX);
    mMax = val != null ? Integer.parseInt(val): DEFAULT_MAX;
  }

  public void onProgressChanged(SeekBar bar, int prog, boolean user) {
    mText.setText("" + toValue(prog));
  }

  public void onStartTrackingTouch(SeekBar bar) {}

  public void onStopTrackingTouch(SeekBar bar) {}

  protected View onCreateDialogView() {
    LinearLayout layout = new LinearLayout(mCtx);
    int val = getValue();
    mText = new TextView(mCtx);
    mText.setText("" + val);
    mBar = new SeekBar(mCtx);
    mBar.setMax(toOffset(mMax));
    mBar.setProgress(toOffset(val));
    mBar.setOnSeekBarChangeListener(this);
    layout.addView(mText);
    layout.addView(mBar, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    return layout;
  }

  protected void onDialogClosed(boolean isResult) {
    if (isResult) {
      setValue(toValue(mBar.getProgress()));
    }
  }

  private int toValue(int ofs) {
    return ofs + mMin;
  }

  private int toOffset(int value) {
    int i = value - mMin;
    return
      i < 0 ? mMin:
      i < mMax ? i:
      mMax;
  }

  private int getValue() {
    int i = SafePreferenceManager.getInt(getSharedPreferences(), getKey(), mMin);
    return
      i < mMin ? mMin :
      i < mMax ? i: mMax;
  }

  private void setValue(int value) {
    SharedPreferences.Editor ed = getEditor();
    ed.putInt(getKey(), value);
    ed.commit();
  }
}
